﻿package level4.grid_case.grid
{
	/**
	 * 寻路中用到的网格
	 * */
	public class Grid
	{
		private var _startNode:Node;
		private var _endNode:Node;
		private var _nodes:Array;
		private var _numCols:int;
		private var _numRows:int;
		
		public function Grid(numCols:int,numRows:int)
		{
			_numCols = numCols;
			_numRows = numRows;
			_nodes = [];
			//分布网格
			for(var i:int=0;i<_numCols;i++){
				_nodes[i] = [];
				for(var j:int=0;j<_numRows;j++){
					_nodes[i][j] = new Node(i,j);
				}
			}
		}
		public function getNode(x:int,y:int):Node{
			return _nodes[x][y] as Node;
		}
		public function setEndNode(x:int,y:int):void{
			_endNode = _nodes[x][y] as Node;
		}
		public function setStartNode(x:int,y:int):void{
			_startNode = _nodes[x][y] as Node;
		}
		public function setWalkable(x:int,y:int,value:Boolean):void{
			_nodes[x][y].walkable = value;
		}
		/**
		 * 检测 是否在网格坐标内,
		 * true : 在网格内
		 * false : 出界
		 * */
		public function checkInBounds(x:int,y:int):Boolean{
			if(x < 0 || x >= numRows || y < 0 || y >= numCols ){
				return false;
			}
			return true;
		}
		/**
		 * 重新分配网格,并保留旧数据
		 * cols : 列数
		 * rows : 行数
		 * */
		public function resets(cols:int,rows:int,isSaveOldData:Boolean=true):void{

			var i:int = 0;
			var j:int = 0;

			var newNodes:Array = [];
			for(i=0;i<cols;i++){
				newNodes[i] = [];
				for(j=0;j<rows;j++){
					if(i < _numCols && j < _numRows)
						newNodes[i][j] = _nodes[i][j];
					else
						newNodes[i][j] = new Node(i,j);
				}
			}

			_nodes = newNodes;
			_numCols = cols;
			_numRows = rows;
		}
		
		public function dispose():void{
			for(var i:int=0;i<_numCols;i++){
				for(var j:int=0;j<_numRows;j++){
					if(_nodes[i][j])
						_nodes[i][j].dispose();
					_nodes[i][j] = null;
				}
			}
			
		}
		
		////////////////////////////
		//Getter Setter
		////////////////////////////
		public function get startNode():Node{
			return _startNode;
		}
		public function get endNode():Node{
			return _endNode;
		}
		public function get numCols():int{
			return _numCols;
		}
		public function get numRows():int{
			return _numRows;
		}
		
	}
}